/**
 * @Author: 陈瑞鹏
 * @Date:   2022-11-25 10:24:20
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-01-12 09:24:38
 */

import baozhaEle from "../eles/baozhaEle";
import BaseEle, { campType, soliderType } from "../eles/baseEle";
import bulletEle from "../eles/bulletEle";
import circleEle from "../eles/circleEle";
import descComp from "../views/descCom";
import dieEle from "../eles/dieEle";
import gameCtr, { modelType } from "../ctrs/gameCtr";
import lineCom from "../eles/lineCom";
import mouseCom from "../views/mouseCom";
import { SoundResManager } from "../ctrs/soundCtr";
import triangleCom from "../eles/triangleCom";
import arrowEle from "../eles/arrowEle";
import fireBallEle from "../eles/fireBallEle";
import squareCom from "../eles/squareCom";
import frozenEle from "../eles/frozenEle";
import recoverEle from "../eles/recoverEle";
import BaseGameScene from "../libs/core/BaseGameScene";
import { SceneManager } from "../libs/manager/SceneManager";
import aiCtr from "../ctrs/aiCtr";
import pvpCtr from "../ctrs/pvp/pvpCtr";
import barrackCtr from "../ctrs/barracks/barrackCtr";
import barrackEntity from "../ctrs/barracks/barrackEntity";
import { CirCleState } from "../shared/game/state/CircleState";
import { BaseState } from "../shared/game/state/BaseState";
import { ResState } from "../shared/game/state/ResState";
import { getTimehms } from "../libs/core/utils";
import { ArrowState } from "../shared/game/state/ArrowState";
import timeArrow from "../eles/timeArrow";

//人人对战
const { ccclass, property } = cc._decorator;

@ccclass
export default class warScene extends BaseGameScene {

  @property({ type: cc.Node, tooltip: "鼠标节点" })
  mouseNode: cc.Node = null;

  @property({ type: cc.Animation, tooltip: "鼠标动画" })
  mouseAni: cc.Animation = null;

  @property({ type: cc.Node, tooltip: "元素节点" })
  eleNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "资源节点" })
  resNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "buff节点" })
  effectNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "miner预制体" })
  minerPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "spearman预制体" })
  spearmanPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "guard预制体" })
  guardPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "shield预制体" })
  shieldPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "castle预制体" })
  castlePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "militia预制体" })
  militiaPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "bowman预制体" })
  bowmanPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "swordsman预制体" })
  swordsmanPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "cavalry预制体" })
  cavalryPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "trapped预制体" })
  trappedPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "dogs预制体" })
  dogsPre: cc.Prefab = null;


  @property({ type: cc.Prefab, tooltip: "master预制体" })
  masterPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "fighter预制体" })
  fighterPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "warlock预制体" })
  warlockPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "scarecrow预制体" })
  scarecrowPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "jumpFire预制体" })
  jumpFirePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "logistics预制体" })
  logisticsPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "树预制体" })
  treePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "矿预制体" })
  mineralPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "圈的节点" })
  circleNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "圈预制体" })
  circle2Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "圈预制体" })
  circlePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "三角预制体" })
  trianglePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "四边预制体" })
  squarePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "圈预制体2" })
  circle3Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "线预制体" })
  linePre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "兵营列表" })
  barracks: cc.Node = null;

  @property({ type: cc.Node, tooltip: "描述节点" })
  descNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "怪物1预制体" })
  mon1Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "怪物2预制体" })
  mon2Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "怪物3预制体" })
  mon3Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "怪物4预制体" })
  mon4Pre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "加农炮预制体" })
  cannonPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "子弹预制体" })
  bulletPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "火球预制体" })
  fireBallPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "箭预制体" })
  arrowPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "地雷预制体" })
  shellPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "子弹层" })
  bulletNode: cc.Node = null;

  @property({ type: cc.Animation, tooltip: "震动动画" })
  shakeAni: cc.Animation = null;

  @property({ type: cc.Node, tooltip: "是否结束" })
  overNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "积分" })
  scoreTxt: cc.Label = null;

  @property({ type: cc.Button, tooltip: "重新开始按钮" })
  aginBtn: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "死亡" })
  diePre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "爆炸" })
  baozhaPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "冰冻" })
  frozenPre: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "回复" })
  recoverPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "血迹层" })
  bloodLayer: cc.Node = null;

  @property({ type: cc.Node, tooltip: "ready" })
  readyNode: cc.Node = null;

  @property({ type: cc.Button, tooltip: "音乐按钮" })
  musicBtn: cc.Node = null;

  @property({ type: cc.Node, tooltip: "火的节点" })
  fireNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "尾焰" })
  lzNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "三角圆形" })
  triNode: cc.Node = null;

  @property({ type: cc.Prefab, tooltip: "地雷预制体" })
  dlPre: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "不能生成区域遮罩" })
  pmNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "左边用户昵称" })
  leftNickName: cc.Label = null;

  @property({ type: cc.Sprite, tooltip: "左边头像" })
  leftAvatar: cc.Sprite = null;

  @property({ type: cc.Label, tooltip: "左边金币" })
  leftGoldTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "房间号" })
  roomTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "右边用户昵称" })
  rightNickName: cc.Label = null;

  @property({ type: cc.Sprite, tooltip: "右边头像" })
  rightAvatar: cc.Sprite = null;

  @property({ type: cc.Label, tooltip: "右边金币" })
  rightGoldTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "准备开始描述" })
  readyTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "倒计时" })
  downTimeTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述一" })
  txt1: cc.Label = null;

  @property({ type: cc.Label, tooltip: "描述二" })
  txt2: cc.Label = null;

  public monsterTime: any = false;

  public isPause: boolean = false; //是否暂停

  public timeHandler = null;

  public castleSpr: BaseEle = null; //城堡脚本

  onLoad() {
    super.onLoad();

    gameCtr.ins.curScene = this.node;
    gameCtr.ins.resNode = this.resNode;
    gameCtr.ins.effectNode = this.effectNode;
    gameCtr.ins.eleNode = this.eleNode;
    gameCtr.ins.gameModel = modelType.pvp;


    SoundResManager.getInstance().preload("sound");

    this.node.on("doShakeAni", this.doShakeAni, this);
    this.node.on("gameOver", this.doGameOver, this);
    this.node.on("die", this.onCreateDie, this);
    this.node.on("fireBullet", this.createBullet, this);
    this.node.on("fireBall", this.createBall, this);
    this.node.on("fireArrow", this.createArrow, this);
    this.node.on("baozha", this.onCreateBaozha, this);
    this.node.on("doShell", this.createShell, this);
    this.node.on("frozen", this.doCreateFrozen, this);
    this.node.on("recover", this.doCreateRecover, this);

    this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onMove, this);
    this.node.on(cc.Node.EventType.MOUSE_MOVE, this.onMove, this);
    this.node.on(cc.Node.EventType.TOUCH_END, this.onUp, this);
    this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onUp, this);
    this.node.on(cc.Node.EventType.MOUSE_UP, this.onUp, this);
    this.node.on("updatePlayer", this.updatePlayer, this);
    this.node.on("joinSuc", this.joinSuc, this);

    let childs = this.barracks.children;
    for (let i = 0; i < childs.length; i++) {
      if (gameCtr.ins.barracksArr[i]) {
        childs[i].on(cc.Node.EventType.TOUCH_START, this.onBarrckDown, this);

        cc.resources.load(gameCtr.ins.barracksArr[i].iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
          childs[i].getComponentInChildren(cc.Sprite).spriteFrame = sp;
        })
      } else {
        cc.resources.load("ele/kb", cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
          childs[i].getComponentInChildren(cc.Sprite).spriteFrame = sp;
        })
      }
    }

    this.initPvp();

  }

  public onDisable(): void {
    super.onDisable();
  }

  /**
   * 初始化
   */
  public initPvp() {
    if (!pvpCtr.ins) {
      new pvpCtr();
    }

    // 监听数据状态事件
    // 新箭矢发射（仅表现）
    pvpCtr.ins.gameSystem.onNewArrow.push(v => { this._onNewArrow(v) });


    //断线 2 秒后自动重连
    pvpCtr.ins.client.flows.postDisconnectFlow.push(v => {
      if (pvpCtr.ins) {
        setTimeout(() => {
          if (pvpCtr.ins)
            pvpCtr.ins.join().then(res => {
              // this.doPmUpdate();
            });
        }, 2000)
      }
      return v;
    });
    pvpCtr.ins.join().then(res => {
      // this.doPmUpdate();
    });

    /**
     * 创建机器人对战
     */
    // setTimeout(() => {
    //   pvpCtr.ins.sendClientInput({
    //     type: "RobotJoin",
    //     robotId: pvpCtr.ins.selfPlayerId * -1,
    //     nickName: Math.floor(Math.random() * 100) + '',
    //     avatar: gameCtr.ins.avatar,
    //     gold: 120,
    //     team: pvpCtr.ins.team == 1 ? 2 : 1,
    //     roomId: pvpCtr.ins.roomId + "",
    //     roomName: pvpCtr.ins.roomName,
    //   })
    // }, 5000);

    this.updatePlayer();

  }

  private async _onNewArrow(arrowState: ArrowState) {

    let arrow = pvpCtr.ins.arrowEles[arrowState.id];

    // 已经存在
    if (arrow) {
      return;
    }

    let playerState = pvpCtr.ins.state.players.find(v => v.id === arrowState.fromPlayerId);
    console.log("playerState");
    console.log(playerState);
    if (!playerState) {
      return;
    }

    let baseEle: BaseEle = pvpCtr.ins.baseEles[arrowState.baseStateId];
    if (baseEle && baseEle.poolName == "cannon") {
      let target = cc.v2(arrowState.targetPos.x, arrowState.targetPos.y);
      var deltax: number = target.x - arrowState.startPos.x
      var deltay: number = target.y - arrowState.startPos.y;
      let angle = 0;

      if (deltax == 0) {
        if (target.y >= arrowState.startPos.y) {
          deltax = 0.0000001
        } else {
          deltax = -0.0000001
        }
      }
      if (deltay == 0) {
        if (target.x >= arrowState.startPos.x) {
          deltay = 0.0000001
        } else {
          deltay = -0.0000001
        }
      }

      if (deltax > 0 && deltay > 0) {
        angle = Math.atan(Math.abs(deltay / deltax))           // 第一项限
      } else if (deltax < 0 && deltay > 0) {
        angle = Math.PI - Math.atan(Math.abs(deltay / deltax))          // 第二项限
      } else if (deltax < 0 && deltay < 0) {
        angle = Math.PI + Math.atan(Math.abs(deltay / deltax))          // 第三项限
      } else {
        angle = 2 * Math.PI - Math.atan(Math.abs(deltay / deltax))         // 第四项限
      }

      baseEle.node.angle = angle * 180 / Math.PI + 90 + 180;
    }


    // 创建新的箭矢显示
    let node = gameCtr.ins.poolObj['timeArrow'].get();
    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj["timeArrow"]);
    }
    console.log(node)
    this.bulletNode.addChild(node);
    // node.setPosition(cc.v2(0, 0));
    arrow = pvpCtr.ins.arrowEles[arrowState.id] = node.getComponent(timeArrow)!;
    arrow.init(arrowState, pvpCtr.ins.state.now);
  }

  /**
   * 进入房间成功
   */
  joinSuc() {
    if (pvpCtr.ins.isStarte) return;
    pvpCtr.ins.isStarte = true;
    this.doPmUpdate();
    this.readyNode.active = true;
    // this.initWar();
  }

  /**
   * 点击开始准备
   */
  onReady() {
    pvpCtr.ins.sendClientInput({
      type: "PlayerReady",
    })

  }

  doPmUpdate() {
    if (this.pmNode)
      if (pvpCtr.ins.team == 2) {
        this.pmNode.x = 333.5;
      } else if (pvpCtr.ins.team == 1) {
        this.pmNode.x = -333.5;
      }
  }

  /**
   * 创建冰冻
   */
  doCreateFrozen(pos, campType) {
    let node = gameCtr.ins.poolObj['frozen'].get();
    if (!node) {
      node = cc.instantiate(this.frozenPre);
    }
    node.setPosition(pos);
    node.getComponent(frozenEle).setInfo({
      life: 600,
      campType: campType,
    })
    gameCtr.ins.effectNode.addChild(node);
  }

  /**
   * 创建回复
   */
  async doCreateRecover(pos, targetPos, aoeNum, type: soliderType = soliderType.master) {
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['recover'].get();

      if (!node) {
        node = await cc.instantiate(this.fireBallPre);
      }

      node.setPosition(pos.x, pos.y);

      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(recoverEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }
  }


  /**
   * 创建死亡动画
   */
  async onCreateDie(e) {
    let node = gameCtr.ins.poolObj['die'].get();
    if (!node) {
      node = await cc.instantiate(this.diePre);
    }
    // console.log(e);
    if (!node) return;
    let nPos = this.bloodLayer.convertToNodeSpaceAR(e);
    node.setPosition(nPos);
    // console.log(nPos);
    node.getComponent(dieEle).setInfo();
    this.bloodLayer.addChild(node);
  }

  /**
   * 创建爆炸动画
   */
  async onCreateBaozha(e, aoeNum = 5, campType = 1) {
    let node = gameCtr.ins.poolObj['baozha'].get();
    if (!node) {
      node = await cc.instantiate(this.baozhaPre);
    }
    // console.log(e);
    let nPos = this.bloodLayer.convertToNodeSpaceAR(e);
    node.setPosition(nPos);
    // console.log(nPos);
    node.getComponent(baozhaEle).setInfo({ aoeNum: aoeNum, campType: campType });
    this.bloodLayer.addChild(node);
  }


  async doCreateDl() {
    let c = gameCtr.ins.poolObj["dl"].get();
    let res = { iconUrl: "ele/dl", harvest: 0, attack: 0, hp: 30, namePos: cc.v2(-200, 190), poolName: "dl", type: soliderType.dl };
    if (!c) {
      if (res.poolName == "tree") {
        c = await cc.instantiate(this.treePre);
      } else if (res.poolName == "mineral") {
        c = await cc.instantiate(this.mineralPre);
      } else if (res.poolName == "dl") {
        c = await cc.instantiate(this.dlPre);
      }
    }
    let spr = c.getComponent(BaseEle)
    spr.setInfo(res);
    spr.initSp(res.iconUrl);
    let n = Math.random() * 380 + 150;
    let x = (Math.random() < 0.5 ? -1 : 1) * n;
    let y = Math.random() * 480 - 240;
    c.setPosition(cc.v2(x, y));

    gameCtr.ins.dlNum++;
    gameCtr.ins.resNode.addChild(c);
  }

  /**
   * 更新玩家信息ui
   */
  updatePlayer() {
    if (!pvpCtr.ins) return;
    if (!pvpCtr.ins.state) return;
    //倒计时
    let now = new Date().getTime();
    this.downTimeTxt.string = getTimehms((pvpCtr.ins.state.gameOverTime - now) * 0.001);

    let leftPlayer = pvpCtr.ins.state.players.find(v => v.team == 2);
    let rightPlayer = pvpCtr.ins.state.players.find(v => v.team == 1);

    if (leftPlayer) {
      this.leftNickName.string = `${leftPlayer.nickName.substring(0, 8)}`;
      this.leftGoldTxt.string = `${leftPlayer.gold}`;
      let iconUrl = barrackCtr.ins.getBarrackById(Number(leftPlayer.avatar)).iconUrl;
      cc.resources.load(iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
        if (err) return;
        if (this.leftAvatar)
          this.leftAvatar.spriteFrame = sp;
      })
    } else {
      this.leftNickName.string = ``;
      this.leftGoldTxt.string = `0`;
      this.leftAvatar.spriteFrame = null;
    }

    if (rightPlayer) {
      this.rightNickName.string = `${rightPlayer.nickName.substring(0, 8)}`;
      this.rightGoldTxt.string = `${rightPlayer.gold}`;
      let iconUrl = barrackCtr.ins.getBarrackById(Number(rightPlayer.avatar)).iconUrl;
      cc.resources.load(iconUrl, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
        if (err) return;
        if (this.rightAvatar)
          this.rightAvatar.spriteFrame = sp;
      })
    } else {
      this.leftNickName.string = ``;
      this.leftGoldTxt.string = `0`;
      this.leftAvatar.spriteFrame = null;
    }

    let player = leftPlayer || rightPlayer;
    this.roomTxt.string = player && player.roomName;
  }

  /**
   * 点击
   * @param e 
   */
  onBarrckDown(e) {
    // console.log("onBarrckDown")
    // console.log(e.currentTarget.name)
    gameCtr.ins.selectData = null;
    let data = null;
    switch (e.currentTarget.name) {
      case "item0":
        data = gameCtr.ins.barracksArr[0];
        break;
      case "item1":
        data = gameCtr.ins.barracksArr[1];
        break;
      case "item2":
        data = gameCtr.ins.barracksArr[2];
        break;
      case "item3":
        data = gameCtr.ins.barracksArr[3];
        break;
      case "item4":
        data = gameCtr.ins.barracksArr[4];
        break;
      case "item5":
        data = gameCtr.ins.barracksArr[5];
        break;
      case "item6":
        data = gameCtr.ins.barracksArr[6];
        break;
    }
    if (gameCtr.ins.gold < data.need) return; //金币不足
    if (data == gameCtr.ins.selectData) return;
    gameCtr.ins.selectData = data;
    e.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    e.currentTarget.off(cc.Node.EventType.TOUCH_END);
    // let nowPos: any = e.getLocation();
    // let pos = this.node.convertToNodeSpaceAR(nowPos);

    this.mouseNode.getComponent(mouseCom).drawSp(gameCtr.ins.selectData.iconUrl);
    e.currentTarget.on(cc.Node.EventType.TOUCH_CANCEL, this.onCreateCirle, this);
    e.currentTarget.on(cc.Node.EventType.TOUCH_END, this.onCreateCirle2, this);
  }

  /**
   * 创建
   * @param touch 
   */
  onCreateCirle(touch) {
    touch.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    touch.currentTarget.off(cc.Node.EventType.TOUCH_END);

    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    if (pvpCtr.ins.team == 2 && pos.x > 0) return; //不能在 敌方创建
    if (pvpCtr.ins.team == 1 && pos.x < 0) return; //不能在 敌方创建
    if (pos.y < -200) {
      gameCtr.ins.selectData = null;
      this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
      return;
    };

    this.doCreate(touch);
  }

  onCreateCirle2(touch) {
    touch.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL);
    touch.currentTarget.off(cc.Node.EventType.TOUCH_END);

    gameCtr.ins.selectData = null;
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
  }

  /**
   * 执行
   * @param touch 
   * @returns 
   */
  async doCreate(touch) {
    if (this.isPause) return;
    if (gameCtr.ins.isOver) return;
    if (!gameCtr.ins.selectData) return;
    // touch.currentTarget.off(cc.Node.EventType.TOUCH_START);
    if (gameCtr.ins.gold < gameCtr.ins.selectData.need) {
      SceneManager.getInstance().pushLayer("tipLayer", "金币不足");
      return; //金币不足
    }

    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);

    let barrackEny: barrackEntity = barrackCtr.ins.getBarrackById(Number(gameCtr.ins.selectData.id));
    let pos0 = pos;
    let pos1 = cc.v2(0, 0);
    let pos2 = cc.v2(0, 0);
    let pos3 = cc.v2(0, 0);
    let pos4 = cc.v2(0, 0);

    if (barrackEny.cirCleType == "line") {
      pos0 = cc.v2(0, 0);
      pos1 = cc.v2(0, 0);
      pos2 = pos;
    } else if (barrackEny.cirCleType == "triangle") {
      pos0 = cc.v2(0, 0);
      pos1 = pos;
      pos2 = cc.v2(pos.x, pos.y + 120);
      pos3 = cc.v2(pos.x + 120, pos.y);
    } else if (barrackEny.cirCleType == "square") {
      pos0 = cc.v2(0, 0);
      pos1 = pos;
      pos2 = cc.v2(pos.x + 120, pos.y);
      pos3 = cc.v2(pos.x + 120, pos.y + 120);
      pos4 = cc.v2(pos.x, pos.y + 120);
    }

    let createInfo: any = this.getBaseCreateInfo(barrackEny, pos);

    createInfo.then((res => {
      console.log(res.targetPosArr.length)
      pvpCtr.ins.sendClientInput({
        type: "BaseCreate",
        pos: pos0,
        num: barrackEny.num,
        cirCleType: barrackEny.cirCleType,
        pos1: pos1,
        pos2: pos2,
        pos3: pos3,
        pos4: pos4,
        startPosArr: res.startPosArr,
        poolName: gameCtr.ins.selectData.poolName,
        targetPosArr: res.targetPosArr,
        nodeIndex: 0,
        moveSpeed: 120 * barrackEny.speedXs,
        speedX: 1,
        eleType: res.eleType,
        campType: pvpCtr.ins.team == 1 ? campType.mine : campType.enemy,
        harvest: barrackEny.harvest,
        harvestTime: 30,
        attack: barrackEny.attack,
        hp: barrackEny.hp,
        maxHp: barrackEny.hp,
        isCanMove: true,
        intval: barrackEny.gs,
        team: pvpCtr.ins.team,
        baseId: barrackEny.id,
        offArr: res.offArr,
        needGold: barrackEny.need,
      })

      // gameCtr.ins.gold -= gameCtr.ins.selectData.need;
      // this.updateGold();
      gameCtr.ins.selectData = null;
      SoundResManager.getInstance().PlayBGM();
      SoundResManager.getInstance().Play("create");
      this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
    }))

  }

  /**
   * 获取创建数据
   * @param barrackEny 
   * @param pos 
   * @returns 
   */
  async getBaseCreateInfo(barrackEny: barrackEntity, pos) {
    let startPosArr = [pos];

    let offArr = [cc.v2(0, 0)];

    let targetPosArr = [];

    let eleType = soliderType.dogs;

    for (let i = 0; i < barrackEny.num; i++) {
      switch (barrackEny.poolName) {
        case "dogs":
          startPosArr.push(cc.v2(Math.random() * 200 - 100 + pos.x, Math.random() * 120 - 70 + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.dogs;
          break;
        case "miner":
          startPosArr.push(cc.v2(Math.random() * 150 - 75 + pos.x, Math.random() * 90 - 52 + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.miner;
          break;
        case "spearman":
          let posArr = [
            cc.v2(-50, 12.5), cc.v2(-50, -12.5),
            cc.v2(-25, 25,), cc.v2(-25, 0), cc.v2(-25, -25),
            cc.v2(0, 37.5), cc.v2(0, 12.5), cc.v2(0, -12.5), cc.v2(0, -37.5),
            cc.v2(25, 25,), cc.v2(25, 0), cc.v2(25, -25),
          ]
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.spearman;
          break;
        case "guard":
          posArr = [cc.v2(-20, 35), cc.v2(35, 5)];
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.guard;
          break;
        case "shield":
          posArr = [
            cc.v2(-13, 13,), cc.v2(-13, -13),
            cc.v2(13, 13), cc.v2(13, -13),
          ]
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [cc.v2(0, 0), cc.v2(0, 0)];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.shield;
          break;
        case "militia":
          posArr = [
            cc.v2(-18, 18,), cc.v2(-18, -18), cc.v2(0, 0),
            cc.v2(18, 18), cc.v2(18, -18),
          ]
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [cc.v2(0, 0), cc.v2(0, 0)];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.militia;
          break;
        case "bowman":
          posArr = [cc.v2(0, 0), cc.v2(-25, 25), cc.v2(25, 25), cc.v2(-25, -25), cc.v2(25, -25)];
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.bowman;
          break;
        case "swordsman":
          posArr = [cc.v2(0, 0), cc.v2(-20, 20), cc.v2(20, 20)];
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.swordsman;
          break;
        case "cavalry":
          posArr = [cc.v2(25, -25), cc.v2(-25, 25), cc.v2(25, 25), cc.v2(-25, -25)];
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.swordsman;
          break;
        case "trapped":
          let b = (700 / Math.max(Math.abs(pos.y), Math.abs(pos.x)));
          startPosArr.push(pos);
          targetPosArr = [cc.v2(pos.x * b, pos.y * b)];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.trapped;
          break;
        case "master":
          startPosArr.push(cc.v2(Math.random() * 100 - 50 + pos.x, Math.random() * 60 - 35 + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.master;
          break;
        case "fighter":
          posArr = [
            cc.v2(-25, 25,), cc.v2(-25, -25),
            cc.v2(25, 25,), cc.v2(25, -25),
          ];
          startPosArr.push(cc.v2(posArr[i].x + pos.x, posArr[i].y + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(posArr[i].x, posArr[i].y));
          eleType = soliderType.fighter;
          break;
        case "scarecrow":
          startPosArr.push(pos);
          eleType = soliderType.scarecrow;
          offArr.push(cc.v2(0, 0));
          break;
        case "jumpFire":
          startPosArr.push(pos);
          eleType = soliderType.jumpFire;
          targetPosArr = [cc.v2(-540, 240), cc.v2(-540, -200), cc.v2(540, -200), cc.v2(540, 240)];
          offArr.push(cc.v2(0, 0));
          break;
        case "logistics":
          startPosArr.push(cc.v2(Math.random() * 100 - 50 + pos.x, Math.random() * 60 - 35 + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.logistics;
          break;
        case "warlock":
          startPosArr.push(cc.v2(Math.random() * 100 - 50 + pos.x, Math.random() * 60 - 35 + pos.y));
          targetPosArr = [];
          offArr.push(cc.v2(0, 0));
          eleType = soliderType.warlock;
          break;
      }
    }

    return { startPosArr, offArr, targetPosArr, eleType };
  }


  /**
   * 创建地雷
   * @param pos 
   */
  async createShell(pos = null, wPos = null) {
    let node: cc.Node = gameCtr.ins.poolObj['shell'].get();
    if (!node) {
      node = await cc.instantiate(this.shellPre);
    }
    if (wPos) {
      pos = this.eleNode.convertToNodeSpaceAR(wPos);
    }

    node.setPosition(pos.x, pos.y);
    // node.angle = Math.random() * 20 - 10;
    let sprn = node.getComponent(BaseEle);
    sprn.setInfo({
      attack: 1, harvest: 0, hp: 1, type: soliderType.shell, isCanMove: false, poolName: "shell"
    })
    this.eleNode.addChild(node);
  }

  /**
   * 创建火球
   * @param pos 
   * @param targetPos 
   * @param aoeNum 
   * @param type 
   */
  async createBall(pos, targetPos, aoeNum, type: soliderType = soliderType.master) {
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['fireBall'].get();

      if (!node) {
        node = await cc.instantiate(this.fireBallPre);
      }

      node.setPosition(pos.x, pos.y);

      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(fireBallEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }
  }

  /**
   * 创建加农炮 炮弹
   */
  async createBullet(pos, targetPos, aoeNum, type: soliderType = soliderType.cannon, campType) {
    // console.log(pos, targetPos);
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['bullet'].get();

      if (!node) {
        node = await cc.instantiate(this.bulletPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(bulletEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }

  }


  /**
   * 创建 箭
   */
  async createArrow(pos, targetPos, aoeNum, type: soliderType = soliderType.cannon, campType) {
    // console.log(pos, targetPos);
    if (pos && targetPos) {
      let node: cc.Node = gameCtr.ins.poolObj['arrow'].get();

      if (!node) {
        node = await cc.instantiate(this.arrowPre);
      }

      node.setPosition(pos.x, pos.y);
      // node.angle = Math.random() * 20 - 10;
      let sprn = node.getComponent(arrowEle);
      sprn.setTargetPos(pos, targetPos, aoeNum, type, campType);
      this.bulletNode.addChild(node);
    }
  }

  /**
   * 点击圆圈
   * @param e 
   */
  onCircleDown(e) {
    e.currentTarget.on(cc.Node.EventType.TOUCH_MOVE, this.onCircleMove, this);
    e.currentTarget.color = new cc.Color().fromHEX("#ffffff");
    // console.log(e.currentTarget);
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorHold");
  }

  /**
   * 移动圆圈
   * @param e 
   */
  onCircleMove(e) {
    let nowPos: any = e.getLocation();
    let pos = this.circleNode.convertToNodeSpaceAR(nowPos);
    e.currentTarget.on(cc.Node.EventType.TOUCH_END, this.onCirCleUp, this);
    e.currentTarget.on(cc.Node.EventType.TOUCH_CANCEL, this.onCirCleUp, this);
    // e.currentTarget.setPosition(pos);
    pvpCtr.ins.sendClientInput({
      type: "CircleMove",
      pos: pos,
      onePos: cc.v2(0, 0),
      twoPos: cc.v2(0, 0),
      threePos: cc.v2(0, 0),
      fourPos: cc.v2(0, 0),
      circleId: Number(e.currentTarget.name),
    })
  }

  onCirCleUp(e) {
    e.currentTarget.off(cc.Node.EventType.TOUCH_END, this.onCirCleUp, this);
    e.currentTarget.off(cc.Node.EventType.TOUCH_CANCEL, this.onCirCleUp, this);
    let colorStr = "#00DBFF";
    if (e.currentTarget.name == "circle3") {
      colorStr = "#8F57FC";
    }
    e.currentTarget.color = new cc.Color().fromHEX(colorStr);
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
  }

  onMove(touch) {
    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    this.mouseNode.active = true;
    this.mouseNode.setPosition(pos);

    if (gameCtr.ins.isMoveTriangle) {
      this.triNode.active = true;
    } else {
      this.triNode.active = false;
    }
    /**
     * 判断与兵营子元素是否相交
     */
    let childs = this.barracks.children;
    this.descNode.active = false;
    for (let i = 0; i < childs.length; i++) {
      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 40 && gameCtr.ins.barracksArr[i]) {
        this.descNode.active = true;
        this.descNode.getComponent(descComp).drawUi(gameCtr.ins.barracksArr[i], childs[i].getPosition());
        break;
      }
    }

    if (!gameCtr.ins.isFire) return;

    childs = this.eleNode.children;

    for (let i = 0; i < childs.length; i++) {
      let ele: cc.Node = childs[i];
      // console.log("hurtBlood");
      if (!ele) {
        // console.log("hurtBlood");
        continue;
      }

      let spr = ele.getComponent(BaseEle);
      if (spr.type != soliderType.monster) continue;

      if (spr.isFire) continue;

      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 20) {
        // let dir = 1;
        // SoundResManager.getInstance().Play("fire");
        spr.doFire(nowPos);
      }
    }
  }

  onUp(touch) {

    let nowPos: any = touch.getLocation();
    let pos = this.node.convertToNodeSpaceAR(nowPos);
    gameCtr.ins.isFire = false;
    if (this.timeHandler)
      clearTimeout(this.timeHandler);

    this.lzNode.active = false;

    this.triNode.active = false;
    this.mouseNode.getComponent(mouseCom).drawSp("ele/HandCursorIdle");
    this.mouseNode.getComponent(mouseCom).playAni("mouseIdle");

    this.mouseNode.active = false;

    if (this.isPause) return;

    if (gameCtr.ins.isFire) return;

    /**
     * 判断与兵营子元素是否相交
     */
    let childs = this.eleNode.children;

    for (let i = 0; i < childs.length; i++) {
      let ele: cc.Node = childs[i];
      // console.log("hurtBlood");
      if (!ele) {
        // console.log("hurtBlood");
        continue;
      }

      if (ele.getComponent(BaseEle).type != soliderType.monster) continue;

      let dis = Math.sqrt(Math.pow(this.mouseNode.x - childs[i].x, 2) + Math.pow(this.mouseNode.y - childs[i].y, 2));
      // console.log(dis, "dis")
      if (dis < 20) {
        let dir = 1;
        SoundResManager.getInstance().Play("click");
        ele.getComponent(BaseEle).doFly(dir);
      }
    }
  }

  /**
   * 播放震动
   */
  doShakeAni() {
    this.shakeAni.stop();
    this.shakeAni.play("shake");
  }

  /**
   * 
   * @param dt 
   * @returns 
   */
  doGameOver() {
    this.overNode.active = true;
    // this.scoreTxt.string = `积分:${gameCtr.ins.score}`;
    this.readyNode.active = false;
    gameCtr.ins.monsterInter = 350;
    gameCtr.ins.resTime = 0;
    gameCtr.ins.dlNum = 0;
    this.unscheduleAllCallbacks();
    this.monsterTime = false;
  }


  /**
   * 返回开始场景
   */
  onBack() {
    this.readyNode.active = false;
    pvpCtr.ins.Leave();
    this.unscheduleAllCallbacks();
    this.monsterTime = false;

    cc.find("loadNode").active = true;
    SceneManager.getInstance().loadScene("startScene", true, () => {
      cc.find("loadNode").active = false;
    });

  }

  /**
  * 点击音乐
  */
  onMusic() {
    gameCtr.ins.isMusic = !gameCtr.ins.isMusic;

    let url = "ele/music_1";
    if (gameCtr.ins.isMusic) {
      url = "ele/music_1";
      SoundResManager.getInstance().PlayBGM();
    } else {
      url = "ele/music_2";
      SoundResManager.getInstance().StopBGM();
    }
    let that = this;
    cc.resources.load(url, cc.SpriteFrame, (err, sp: cc.SpriteFrame) => {
      that.musicBtn.getComponentInChildren(cc.Sprite).spriteFrame = sp;
    })
  }

  update(dt) {
    if (!pvpCtr.ins) return;
    pvpCtr.ins.localTimePast();

    if (pvpCtr.ins.state.gameState == 1) {
      this.readyNode.active = true;
      this.overNode.active = false;
      if (pvpCtr.ins.currentPlayerState && pvpCtr.ins.currentPlayerState.isReady) {
        this.readyTxt.string = "等待对手";
      } else {
        this.readyTxt.string = "准备";
      }
    } else if (pvpCtr.ins.state.gameState == 2) {
      this.readyNode.active = false;
      this.overNode.active = false;
    } else if (pvpCtr.ins.state.gameState == 3) {
      this.readyNode.active = false;
      this.overNode.active = true;
      // console.log(pvpCtr.ins.state.resultData);
      if (pvpCtr.ins.state.resultData) {
        this.txt1.string = pvpCtr.ins.state.resultData.txt1 || "";
        this.txt2.string = pvpCtr.ins.state.resultData.txt2 || "";
      }

      this.scheduleOnce(() => {
        // pvpCtr.ins.Leave();
        this.onBack();
      }, 1);
    }

    this.updatePlayer();
    this.updateCirCleEle();
    this.updateBaseEle();
    this.updateResEle();
  }

  initWar() {

    let pos0 = pvpCtr.ins.team == 2 ? cc.v2(-380, 0) : cc.v2(380, 0);
    let pos1 = cc.v2(0, 0);
    let pos2 = cc.v2(0, 0);
    let pos3 = cc.v2(0, 0);
    let pos4 = cc.v2(0, 0);
    console.log(pos0);
    pvpCtr.ins.sendClientInput({
      type: "BaseCreate",
      pos: cc.v2(0, 0),
      num: 1,
      cirCleType: "",
      pos1: pos1,
      pos2: pos2,
      pos3: pos3,
      pos4: pos4,
      startPosArr: [pos0],
      poolName: "castle",
      targetPosArr: [],
      nodeIndex: 0,
      moveSpeed: 0,
      speedX: 1,
      eleType: soliderType.castle,
      campType: pvpCtr.ins.team == 1 ? campType.mine : campType.enemy,
      harvest: 0,
      harvestTime: 0,
      attack: 1,
      hp: 100,
      maxHp: 100,
      isCanMove: true,
      intval: 0,
      team: pvpCtr.ins.team,
      baseId: 0,
      offArr: [cc.v2(0, 0)],
      needGold: 0,
    })
  }


  /**
   * 更新圈
   */
  private updateCirCleEle() {
    let circleArr = pvpCtr.ins.state.cirCleEles || [];
    for (let circleState of circleArr) {
      let circleEle = pvpCtr.ins.cirCleEles[circleState.id];
      if (circleState.cirCleType) {
        if (!circleEle) {
          // console.log(circleEle)
          this.createCirCle(circleState).then(res => {
            pvpCtr.ins.cirCleEles[circleState.id] = res;
          });
        } else {
          circleEle.hp = circleState.hp;
          // if (circleState.playerId == pvpCtr.ins.selfPlayerId)
          //   console.log(circleState, "circleState.pos");
          circleEle.node.setPosition(cc.v2(circleState.pos.x, circleState.pos.y));
          // console.log(circleState.cirCleType)
          if (circleState.cirCleType == "line") {
            circleEle.pos1.setPosition(cc.v2(circleState.pos1.x, circleState.pos1.y));
            circleEle.pos2.setPosition(cc.v2(circleState.pos2.x, circleState.pos2.y));
          } else if (circleState.cirCleType == "triangle") {
            circleEle.pos1.setPosition(cc.v2(circleState.pos1.x, circleState.pos1.y));
            circleEle.pos2.setPosition(cc.v2(circleState.pos2.x, circleState.pos2.y));
            circleEle.pos3.setPosition(cc.v2(circleState.pos3.x, circleState.pos3.y));
          } else if (circleState.cirCleType == "square") {
            circleEle.pos1.setPosition(cc.v2(circleState.pos1.x, circleState.pos1.y));
            circleEle.pos2.setPosition(cc.v2(circleState.pos2.x, circleState.pos2.y));
            circleEle.pos3.setPosition(cc.v2(circleState.pos3.x, circleState.pos3.y));
            circleEle.pos4.setPosition(cc.v2(circleState.pos4.x, circleState.pos4.y));
          }

          // if (circleState.isMove)
          circleEle.drawGrap();
        }
      }
    }

    for (let ele in pvpCtr.ins.cirCleEles) {
      if (!circleArr.find(v => v.id == Number(ele))) {
        pvpCtr.ins.cirCleEles[ele].recover();
        delete pvpCtr.ins.cirCleEles[ele];
      }
    }
  }

  /**
   * 创建
   */
  private async createCirCle(circleState: CirCleState) {

    if (circleState.cirCleType == "circle" || circleState.cirCleType == "circle2" || circleState.cirCleType == "circle3") {

      let circle = gameCtr.ins.poolObj[circleState.cirCleType].get();
      if (!circle) {
        if (circleState.cirCleType == "circle") {
          circle = await cc.instantiate(this.circlePre);
        } else if (circleState.cirCleType == "circle2") {
          circle = await cc.instantiate(this.circle2Pre);
        } else if (circleState.cirCleType == "circle3") {
          circle = await cc.instantiate(this.circle3Pre);
        }
      }
      circle.setPosition(circleState.pos);

      let spr = circle.getComponent(circleEle);

      spr.hp = circleState.hp;

      spr.circleId = circleState.id;

      circle.name = `${circleState.id}`;

      spr.poolName = circleState.cirCleType;

      if (circleState.playerId != pvpCtr.ins.selfPlayerId) {
        spr.drawColor("#FC6B3D");
      } else {
        spr.drawColor("#00DBFF");
        circle.on(cc.Node.EventType.TOUCH_START, this.onCircleDown, this);
      }

      this.circleNode.addChild(circle);

      return spr;
    } else if (circleState.cirCleType == "line") {
      let line = gameCtr.ins.poolObj['line'].get();
      if (!line) {
        line = await cc.instantiate(this.linePre);
      }
      line.setPosition(cc.v2(0, 0));

      let spr = line.getComponent(lineCom);

      spr.hp = circleState.hp;

      spr.circleId = circleState.id;

      spr.playerId = circleState.playerId;

      line.name = `${circleState.id}`;

      if (circleState.playerId == pvpCtr.ins.selfPlayerId) {
        spr.cirCleColor = "#8F57FC";

        spr.grapColor = "#00BDFC"; //线条颜色

      } else {

        spr.cirCleColor = "#FC6B3D";

        spr.grapColor = "#FC6B3D"; //线条颜色
      }

      spr.init(circleState.pos1, circleState.pos2);
      this.circleNode.addChild(line);

      return spr;
    } else if (circleState.cirCleType == "triangle") {
      let triangle = gameCtr.ins.poolObj['triangle'].get();
      if (!triangle) {
        triangle = await cc.instantiate(this.trianglePre);
      }
      triangle.setPosition(cc.v2(0, 0));

      let spr = triangle.getComponent(triangleCom);

      spr.hp = circleState.hp;

      spr.circleId = circleState.id;

      spr.playerId = circleState.playerId;

      triangle.name = `${circleState.id}`;

      if (circleState.playerId == pvpCtr.ins.selfPlayerId) {
        spr.cirCleColor = "#8F57FC";

        spr.grapColor = "#00BDFC"; //线条颜色

      } else {

        spr.cirCleColor = "#FC6B3D";

        spr.grapColor = "#FC6B3D"; //线条颜色
      }


      spr.init(circleState.pos1, circleState.pos2, circleState.pos3);
      this.circleNode.addChild(triangle);

      return spr;
    } else if (circleState.cirCleType == "square") {
      let square = gameCtr.ins.poolObj['square'].get();
      if (!square) {
        square = await cc.instantiate(this.squarePre);
      }
      square.setPosition(cc.v2(0, 0));

      let spr = square.getComponent(squareCom);

      spr.hp = circleState.hp;

      spr.circleId = circleState.id;

      spr.playerId = circleState.playerId;

      square.name = `${circleState.id}`;

      if (circleState.playerId == pvpCtr.ins.selfPlayerId) {
        spr.cirCleColor = "#8F57FC";

        spr.grapColor = "#00BDFC"; //线条颜色

      } else {

        spr.cirCleColor = "#FC6B3D";

        spr.grapColor = "#FC6B3D"; //线条颜色
      }

      spr.init(circleState.pos1, circleState.pos2, circleState.pos3, circleState.pos4);

      this.circleNode.addChild(square);

      return spr;
    }

  }

  /**
   * 更新元素
   */
  private async updateBaseEle() {
    let baseArr = pvpCtr.ins.state.rightBaseEles.concat(pvpCtr.ins.state.leftBaseEles);
    for (let baseState of baseArr) {
      let baseEle = pvpCtr.ins.baseEles[baseState.id];
      //场景上还没有这个baseEle 新建之
      if (!baseEle) {
        this.createBaseEle(baseState, pvpCtr.ins.baseEles);
      } else {
        //根据最新状态 更新baseEle 表现组件
        baseEle.updateState(baseState, pvpCtr.ins.state.now);
      }
    }

    for (let ele in pvpCtr.ins.baseEles) {
      if (!baseArr.find(v => v.id == Number(ele))) {
        pvpCtr.ins.baseEles[ele].recover();
        delete pvpCtr.ins.baseEles[ele];
      }
    }
  }

  /**
   * 创建元素
   * @param baseState 
   * @param arr 
   */
  private async createBaseEle(baseState: BaseState, arr) {
    let node = gameCtr.ins.poolObj[baseState.poolName].get();

    if (!node) {
      node = await cc.instantiate(gameCtr.ins.preObj[baseState.poolName]);
    }
    // console.log(baseState);
    node.setPosition(baseState.pos);

    let spr = node.getComponent(BaseEle);
    spr.setInfo({
      id: baseState.baseId,
      attack: baseState.attack, harvest: baseState.harvest, hp: baseState.hp, type: baseState.type, isCanMove: baseState.isCanMove,
      poolName: baseState.poolName, moveSpeed: baseState.moveSpeed, campType: baseState.campType
    })

    if (pvpCtr.ins.selfPlayerId == baseState.playerId) {
      spr.isSelf = true;
    } else {
      spr.isSelf = false;
    }

    spr.baseStateId = baseState.id;

    this.eleNode.addChild(node);

    arr[baseState.id] = spr;
  }

  /**
   * 更新资源
   */
  private updateResEle() {
    let resArr = pvpCtr.ins.state.resBaseEles;
    for (let resState of resArr) {
      let resEle = pvpCtr.ins.resBaseEle[resState.id];
      //场景上还没有这个resEle 新建之
      if (!resEle) {
        this.createResEle(resState);
      } else {
        //根据最新状态 更新baseEle 表现组件
        resEle.updateResState(resState, pvpCtr.ins.state.now);
      }
    }

    for (let ele in pvpCtr.ins.resBaseEle) {
      if (!pvpCtr.ins.state.resBaseEles.find(v => v.id == Number(ele))) {

        pvpCtr.ins.resBaseEle[ele].recover();
        delete pvpCtr.ins.resBaseEle[ele];
      }
    }
  }

  /**
   * 根据服务器数据创建资源
   * @param resState 
   */
  private async createResEle(resState: ResState) {
    let c = gameCtr.ins.poolObj[resState.poolName].get();
    if (!c) {
      c = await cc.instantiate(gameCtr.ins.preObj[resState.poolName]);
    }
    let spr = c.getComponent(BaseEle)
    spr.setInfo({
      hp: resState.hp,
      poolName: resState.poolName,
      attack: 0,
      harvest: 0,
    });

    spr.initSp(resState.iconUrl);
    c.setPosition(resState.pos);
    spr.baseStateId = resState.id;
    // console.log(resState.id, resState.iconUrl);
    spr.maxHp = resState.maxHp;
    pvpCtr.ins.resBaseEle[resState.id] = spr;
    gameCtr.ins.resNode.addChild(c);
  }
}
